package com.example.quartz.component;

import com.example.quartz.utils.DynamicCompilerJavaUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @author: wlp
 * @description: 描述：执行定时任务
 * @projectName: ScheduleRunnable
 * @date: 2019/10/12
 * @version: V1.0.0
 */
@Data
public class ScheduleRunnable implements Runnable {

    private Object targetBean;
    private Method method;
    private String methodParams;
    private Integer quartzType;
    private String targetContent;
    private String methodName;
    private String className;

    ScheduleRunnable(String beanName, String methodName, String methodParams, Integer quartzType, String targetContent) throws NoSuchMethodException, SecurityException {
        this.className = beanName;
        this.methodName = methodName;
        this.quartzType = quartzType;
        this.targetContent = targetContent;
        this.targetBean = SpringContextHandler.getBean(beanName);
        this.methodParams = methodParams;
        if (StringUtils.isNotBlank(methodParams)) {
            this.method = targetBean.getClass().getDeclaredMethod(methodName, String.class);
        } else {
            this.method = targetBean.getClass().getDeclaredMethod(methodName);
        }
    }

    @Override
    public void run() {
        try {
            if (quartzType.equals(1)) {
                ReflectionUtils.makeAccessible(method);
                if (StringUtils.isNotBlank(methodParams)) {
                    method.invoke(targetBean, methodParams);
                } else {
                    method.invoke(targetBean);
                }
            } else {
                DynamicCompilerJavaUtil.run(targetContent, methodName, className, methodParams);
            }
        } catch (Exception e) {
            throw new RuntimeException("执行定时任务失败", e);
        }
    }
}
